﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WCAD.Kean
{
    public class EntitiesOnLayer
    {
        [CommandMethod("EOL")]

        static public void EOL()

        {

            Document doc =

              Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;


            PromptResult pr =

              ed.GetString("\nEnter name of layer: ");

            if (pr.Status == PromptStatus.OK)

            {

                ObjectIdCollection ents =

                  GetEntitiesOnLayer(pr.StringResult);

                ed.WriteMessage(

                  "\nFound {0} entit{1} on layer {2}",

                  ents.Count,

                  (ents.Count == 1 ? "y" : "ies"),

                  pr.StringResult

                );

            }

        }


        private static ObjectIdCollection

          GetEntitiesOnLayer(string layerName)

        {

            Document doc =

              Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;


            // Build a filter list so that only entities

            // on the specified layer are selected


            TypedValue[] tvs =

              new TypedValue[1] {

            new TypedValue(

              (int)DxfCode.LayerName,

              layerName

            )

                };

            SelectionFilter sf =

              new SelectionFilter(tvs);

            PromptSelectionResult psr =

              ed.SelectAll(sf);


            if (psr.Status == PromptStatus.OK)

                return

                  new ObjectIdCollection(

                    psr.Value.GetObjectIds()

                  );

            else

                return new ObjectIdCollection();

        }
    }
}
